<template>
  <base-modal
    :title="title"
    class="create-project-task-dialog"
    width="676px"
    :show.sync="isShow"
    :mask-closeable="false">
    <div class="add-form task-form">
        <el-form label-position="top" :model="form" :rules="rules" ref="taskForm" >
          <el-form-item :label="$t('projectManage.setting.taskSetting.taskNum')" prop="number">
            <div v-if="isFormEdit" class="task-num">{{ form.taskNumber }}</div>
            <div v-else class="default-no">{{ $t('projectManage.setting.taskSetting.placeholder1') }}</div>
          </el-form-item>
          <el-form-item :label="$t('projectManage.setting.taskSetting.taskName')" prop="projectTaskName">
            <el-input maxlength="20" v-model.trim="form.projectTaskName" :placeholder="$t('projectManage.setting.taskSetting.placeholder2')" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label="$t('projectManage.setting.taskSetting.taskType')" prop="taskFormId">
            <!-- 只有编辑点击过来的的才禁用 -->
            <el-cascader
              ref="cascaderType"
              class="task-cascader"
              :props="taskProps"
              v-model="form.taskFormId"
              :options="typeOptions"
              :disabled="actionType !== 'add'"
              :placeholder="$t('projectManage.setting.taskSetting.placeholder3')"
              @change="handleSelectType($event)"></el-cascader>
          </el-form-item>
          <!-- 任务设置 -->
            <el-form-item :label="$t('projectManage.setting.taskSetting.preTask')" prop="preTaskId">
              <el-select
                class="w-100"
                v-model="form.preTaskId"
                multiple
                filterable
                clearable
                :multiple-limit="10"
                :placeholder="$t('common.placeholder.select')"
              >
                <el-option
                  v-for="item in preTaskOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

          <!-- 计划开始时间（任务类型选择paas的时候才显示）   -->
          <el-form-item v-if="form.taskType === 'PAAS_TASK' && !isEmpty(form.taskFormId)" :label="$t('common.form.type.planStartTime')" prop="projectTaskStartTimeField">
            <el-select
              class="w-100"
              v-model="form.projectTaskStartTimeField"
              filterable
              clearable
              :placeholder="$t('projectManage.setting.taskSetting.timeFieldPlace')"
              :disabled="actionType === 'edit'"
              @change="updateProjectTaskStartTime"
            >
              <el-option
                v-for="item in paasTimeFields"
                :key="`${item.fieldName}_start`"
                :label="item.displayName"
                :value="item.fieldName"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 计划结束时间（任务类型选择paas的时候才显示）   -->
          <el-form-item v-if="form.taskType === 'PAAS_TASK' && !isEmpty(form.taskFormId)" :label="$t('common.form.type.planEndTime')" prop="projectTaskEndTimeField">
            <el-select
              class="w-100"
              v-model="form.projectTaskEndTimeField"
              filterable
              clearable
              :placeholder="$t('projectManage.setting.taskSetting.timeFieldPlace')"
              :disabled="actionType === 'edit'"
              @change="updateProjectTaskEndTime"
            >
              <el-option
                v-for="item in paasTimeFields"
                :key="`${item.fieldName}_end`"
                :label="item.displayName"
                :value="item.fieldName"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('projectManage.setting.taskSetting.projectContent')" prop="projectTaskDesc">
            <el-input  type="textarea" maxlength="500" v-model="form.projectTaskDesc" :placeholder="$t('projectManage.setting.taskSetting.placeholder6')" show-word-limit></el-input>
          </el-form-item>
          <form-builder 
            :fields="fields" 
            mode="mission" 
            class="edit-task-form" 
            ref="taskFieldform" 
            :extraValidations="extraValidations"
            :value="taskformVal" 
            @update="updateForm"
            :formEditingMode="formEditingMode"
            @getDeleteFiles="getDeleteFiles">
            <template slot="expectTime" slot-scope="{ field }">
              <form-item :label="field.displayName"  
                ref="expectTime"
                :propField="field"
                :propValue="taskformVal.expectTime"
                :validation="extraValidations.expectTime"
                >
                <el-input
                  @input="inputChange($event)"
                  v-model="taskformVal.expectTime"
                  :placeholder="(field.placeHolder) ? field.placeHolder : $t('common.placeholder.input2')"
                  :min="0"
                  @change="value => SetUpdate('expectTime', value)"
                  type="number"
                />
              </form-item>
            </template>
            <!-- 计划开始时间 -->
            <template slot="planStartTime" slot-scope="{ field, value }">
              <form-item :label="field.displayName">
                <form-planstarttime :field="field" :value="value" @update="updateForm" :picker-options="planStartPickerOptions"></form-planstarttime>
              </form-item>
            </template>

            <!-- 计划结束时间 -->
            <template slot="planEndTime" slot-scope="{ field, value }">
              <form-item :label="field.displayName">
                <form-planendtime :field="field" :value="value" @update="updateForm" :picker-options="planEndPickerOptions"></form-planendtime>
              </form-item>
            </template>

            <!-- 负责人 -->
            <template slot="managerPerson" slot-scope="{ field, value }">
              <form-item :label="field.displayName">
                <form-user
                  :field="field"
                  :value="value"
                  @update="updateForm"
                  multiple
                  selectFn="user"
                  :selectOptions="managerSelectOptions()"
                />
              </form-item>
            </template>
          </form-builder>
        </el-form>
    </div>
    <div slot="footer">
        <el-button @click="closeDialog">{{$t('common.base.cancel')}}</el-button>
        <!-- 通用任务 和非通用任务编辑 / 提交状态下要展示保存 -->
        <el-button v-if="isShowSaveBtn" :disabled="pending" type="primary" @click="submitForm">{{$t('common.base.save')}}</el-button>
        <!-- 非通用任务 提交和编辑状态都展示下一步按钮 -->
        <el-button v-if="isShowNext" :disabled="pending" type="primary" @click="goCreateForm">{{$t('common.base.nextStep')}}</el-button>
      </div>
  </base-modal>
</template>
<script>

import _ from 'lodash';
import { ConnectorModuleRuleForm } from '@src/modules/connector/components'
import { connectorFromFieldsAddChildren } from '@src/modules/connector/util';
import { createConnectorRuleFormItem } from '@src/modules/connector/util'
import * as ProjectManage from '@src/api/ProjectManage.ts';
import moment from 'moment'
import { openAccurateTab } from '@src/util/platform'
import { getDisabledDate, isEmpty } from 'pub-bbx-utils'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import AuthUtil from '@src/util/auth';
import { getAsyncTaskViewInitData } from '@src/api/InitDataApi'
import i18n from '@src/locales';
import { jumpProjectTypeDetail } from '@src/modules/projectManage/productTypeUtils/jumpPage.js';
import * as FormUtil from '@src/component/form/util'
/* api */
import { getTenantConfigByCodeList } from '@src/api/SettingApi'
import { getFormFieldListInfo } from '@src/api/PassApi.js'
import { getNodeInstanceRelation } from "@src/api/ProjectManage.ts";

export default {
  name: 'create-project-task',
  data() {
    let extraValidations = Object.freeze({
      ifRequired: (type) => {
        if (['expectTime'].includes(type)) {
          let field = this.fields.find(field => field.fieldName === type)
          return !!(field && !field.isNull)
        }

        let isRequired = this.$refs[type]?.showRequired
        if (!isRequired) return false

        return true
      },
      expectTime: () => {
        let type = 'expectTime'
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false

        if (!(this.taskformVal[type])) {
          return this.$refs[type].errMessage = this.$t('common.placeholder.inputSomething', {data1: this.$t('common.projectManage.detail.statistics.text6')})
        }
        return this.$refs[type].errMessage = ''
      },
    })
    return {
      extraValidations,
      title:  '',
      form: {
        projectTaskName: '',
        projectTaskDesc: '',
        taskType: '',
        taskFormId: '',
        preTaskId: [],
        projectTaskStartTimeField: '',
        projectTaskEndTimeField: '',
      },
      rules: {
        projectTaskName: [
          { required: true, message: this.$t('projectManage.setting.taskSetting.placeholder2'), trigger: 'blur' },
          { max: 20, message: this.$t('projectManage.setting.taskSetting.ruleMess1'), trigger: 'blur' }
        ],
        taskFormId: [
          {required: true, message: this.$t('projectManage.setting.taskSetting.placeholder3'), trigger: 'change' }
        ],
      },
      taskProps: {
        multiple: false,
        value: 'id',
        label: 'name',
        emitPath: false,
        children: 'formList',
      },
      pending: false,
      isShow: false,
      isFormEdit: false,
      insertFieldOptionsList:[],
      fromFieldList:[],
      toFieldList:[],
      selectTypeName: '', // 选中的任务类型名称
      fields: [], // 任务类型的表单字段
      taskformVal: {}, // 任务类型表单的值
      preTaskIdList: [],
      actionType: '', // 操作的状态
      typeOptions: [],
      preTaskOption: [], // 前置任务的列表
      workOrderData: {}, // 工单的详情数据
      isShowSaveBtn: true,
      isShowNext: false,
      userInstance: {},
      needServerDeleFiles: [],
      openTime: false,
      paasTimeFields: [],// paas表单时间字段
      isEmpty,
    }
  },
  props: {
    // 项目类型id
    templateId: {
      type: String | Number,
      default: '',
    },
    // 项目详情id
    projectId: {
      type: String | Number,
      default: '',
    },
    // 来源 - 区分是项目详情的编辑还是任务详情的编辑
    source: {
      type: String,
      default: ''
    },
    projectPlanTime: {
      type: Object,
      default: () => ({}),
    }
  },
  components: {
    ConnectorModuleRuleForm
  },
  computed: {
    planStartPickerOptions() {
      let that = this
      return {
        disabledDate(time) {
          return getDisabledDate(time, that.taskformVal?.planEndTime);
        },
      };
    },

    /** 当前登录用户 */
    loginUser() {
      return this.workOrderData?.loginUser || {};
    },
    /** 当前用户的权限 */
    permission() {
      return this.loginUser.authorities || {};
    },
    /* 工单编辑权限 */
    editAuth() {
      return this.hasAuth('TASK_EDIT');
    },
    /* TODO PAAS编辑权限 */
    editPAASAuth() {
      return true;
    },
    /**
    * @description 是否显示编辑按钮
    * 1. 不是审批状态
    * 2. 且 不是暂停状态
    * 3. 且 工单允许编辑 canEditTask
    * 4. 且 工单允许修改 isAllowUpdate
    * 5. 满足以上条件就会显示编辑按钮 无论是否有工单编辑权限TASK_EDIT
    */
    allowEditTask() {
      return !this.isApproving && !this.isPaused && this.workOrderData?.canEditTask && this.workOrderData?.isAllowUpdate && !this.isDelete;
    },

    /**
    * @description 工单是否被删除
    * 在工单删除时不允许做任何操作，只能查询
    * 所有操作的权限应该以此为基础
    */
    isDelete() {
      return this.workOrderData?.task?.isDelete === 1;
    },
    /* 工单是否在审批状态 */
    isApproving() {
      return this.workOrderData?.task?.inApprove == 1;
    },
    /* 工单是否在暂停状态 */
    isPaused() {
      return this.workOrderData?.task?.isPaused == 1;
    },

    planEndPickerOptions() {
      let that = this
      return {
        disabledDate(time) {
          return getDisabledDate(time, that.taskformVal?.planStartTime, true);
        },
      };
    },
    // 是否是通用任务
    isCommonTask() {
      return this.form.taskType === 'COMMON_TASK'
    },
    formEditingMode() {
      return this.actionType == 'edit' ? 'edit' : 'create'
    },
    // 判断任务是否有计划开始时间
    isTaskPlanStatTime() {
      return this.fields?.some(item => item.fieldName === 'planStartTime')
    },
    // 判断任务是否有计划完成时间
    isTaskPlanEndTime() {
      return this.fields?.some(item => item.fieldName === 'planEndTime')
    }
  },
  methods: {
    updateProjectTaskEndTime(value) {
      this.form = {...this.form, projectTaskEndTimeField: value};
    },
    updateProjectTaskStartTime(value) {
      this.form = {...this.form, projectTaskStartTimeField: value};
    },
    // paas查询表单的时间字段
    async queryTimeFields() {
      if(this.form.taskType !== 'PAAS_TASK' || isEmpty(this.form.taskFormId)) {
        this.form.projectTaskStartTimeField = ''
        this.form.projectTaskEndTimeField = ''
        return;
      }

      try {
        this.paasTimeFields = [];
        const { success, data} = await getFormFieldListInfo({templateBizId: this.form.taskFormId});
        if(!success) return;

        this.paasTimeFields = data?.paasFormFieldVOList?.filter(item => ['date'].includes(item.formType));

      } catch (e) {
        console.error(e)
      }
    },

    // 是否含有某一指定权限
    hasAuth(keys) {
      return AuthUtil.hasAuth(this.permission, keys);
    },
    jumpDetail() {
      if (this.isFormEdit && this.source === 'projectTask') {
        jumpProjectTypeDetail({
          templateId: this.templateId,
          id: this.projectId,
        }, true);
        this.isShow = false;
      } else {
        this.$emit('jumpPersonTab');
        // 关闭人员控件
        this.userInstance.close()
      }
    },
    // 负责人配置项目
    managerSelectOptions() {
      return {
        renderDynamicContent: (h, context) => {
          return (
            <div class="projectCustom">
              <span class="projectCustom-left">{i18n.t('common.projectManage.detail.selectProjectTeam')}</span>
              <span class="projectCustom-right" onClick={this.jumpDetail}>{i18n.t('common.projectManage.detail.setProjectTeam')}</span>
            </div>
          )
        },
        getInstance: (instance) => {
          this.userInstance = instance;    
        },
        fetchProjectTeamList: () => { 
          const newParams = {
            projectId: this.projectId
          }
          return ProjectManage.getSelectProjectTeamList(newParams)
        },
        fetchProjectTeamUserList: () => {
          const newParams = {
            projectId: this.projectId
          }
          return ProjectManage.getMemberList(newParams)
        },
        fetchSearchUserList: (params)=>{
          const newParams = {
            ...params,
            projectId:this.projectId
          }
          return ProjectManage.getSearchUserList(newParams)
        },
        fetchSearchMoreUserList:(params)=>{
          const newParams = {
            ...params,
            projectId:this.projectId
          }
          return ProjectManage.getSearchMoreUserList(newParams)
        },
        showRole: false,
        isScreenSelect: false,
        showDepartment: false,
        showServiceProvider: false,
        showProjectTeam: true,
      }
    },
    inputChange(val) {
      if (val?.indexOf('-') >= 0) {
        this.taskformVal.expectTime = this.taskformVal.expectTime.replace('-', '');
      }
      this.$forceUpdate();
    },
    SetUpdate(key, value) {
      this.taskformVal[key] = (Math.floor(Number(value)*100)/100).toFixed(2);
      this.$forceUpdate();
    },
    addRuleFormItem() {
      this.insertFieldOptionsList = [...this.insertFieldOptionsList, createConnectorRuleFormItem()];
    },
    onConnectorSelectRuleFormInputHandler(val) {
      // 添加子属性
      connectorFromFieldsAddChildren(this.fromFieldList);
      this.insertFieldOptionsList = val;
    },
    async openDialog(defaultForm, isEdit, actionType) {
      await this.getTaskTypeData(actionType)
      this.title = isEdit ? this.$t('projectManage.setting.taskSetting.editTask') : this.$t('projectManage.setting.taskSetting.createTask')
      this.actionType = actionType || ''
      this.isFormEdit = isEdit || false
      this.fields = [] // 表单字段重置为空
      this.taskformVal = {} // 重置一下表单字段的值
      this.preTaskIdList = []
      this.isShowSaveBtn = true;
      this.isShowNext = false;

      if (defaultForm) {
        // 回显前置任务
        defaultForm.preTaskInfoList = (defaultForm.preTaskInfoList || []).map((item) => {
          return Object.freeze({
            label: item.name,
            value: item.id,
            ...item
            })
        })
        this.preTaskIdList = defaultForm.preTaskInfoList
        this.isShowNext = defaultForm.taskType && defaultForm.taskType !== 'COMMON_TASK'
        this.$set(this, 'form', _.cloneDeep(defaultForm))
        // 判断是否是工单任务类型
        if (defaultForm.taskType === 'WORK_TASK' && defaultForm.taskBizId) {
          this.getWorkOrderEdit(defaultForm.taskBizId)
        }

      } else {
        this.$set(this, 'form', {projectTaskStartTimeField: '', projectTaskEndTimeField: ''})
        this.$set(this.form, 'projectTaskName', '')
        this.$set(this.form, 'projectTaskDesc', '')
        this.$set(this.form, 'taskType', '')
        this.$set(this.form, 'taskFormId', '')
        this.$set(this.form, 'preTaskId', [])
      }

      // 项目详情页面 初始化下拉表单的所有的字段
      if (this.form.taskType === 'COMMON_TASK')  {
        // 通用任务
        this.initFormList()
      }
      // 只有任务是草稿状态并且附加组件id有值的 时候调用接口
      if (this.form.additionalId && actionType === 'draft' && this.isCommonTask) {
        this.projectToTaskForm()
      }

      this.getOpenTimeConfig()

      this.getPreTaskOption()
      this.$refs['taskForm'].resetFields();
      // 默认获取paas表单字段
      await this.queryTimeFields();
      this.isShow = true
    },

    // 获取是否校验任务计划开始完成时间
    async getOpenTimeConfig() {
      // 新建任务：校验任务的计划开始时间和计划完成时间
      if(this.isFormEdit) return
      try {
        const { data } = await getTenantConfigByCodeList({codeList: ['projectTaskTimeSetting']})

        this.openTime = data?.[0]?.isOpen == 1
      } catch (e) {
        console.error(e)
      }
    },

    // 获取当前是否有编辑工单权限，以及当前工单的状态是否可以编辑
    async getWorkOrderEdit(taskBizId) {
      this.pending = true
      let params = {
        noHistory: 1,
        id: taskBizId
      }
      await getAsyncTaskViewInitData(params).then((res) => {
        this.pending = false
        if (!res.succ) return this.$message.error(res.message)
        this.workOrderData = res.data?.initJson || {}
        console.log(this.workOrderData, 'this.workOrderDatathis.workOrderData')
      })
    },

    // 跳转到对应表单的新建页面
    async goCreateForm() {
      // 非通用任务点击下一步的时候，都要请求保存任务接口
      // 跳转之前，表单的字段先必填，请求保存接口之后，再去保存新建表单的字段
      // taskFormId 表单类型的id 工单/事件/paas
      this.$refs['taskForm'].validate( async(valid, object) => {
        // 校验paas任务的计划开始时间和计划完成时间字段是否一样
        if(this.form.taskType === 'PAAS_TASK'
            && this.form.projectTaskStartTimeField && this.form.projectTaskEndTimeField
            && this.form.projectTaskStartTimeField === this.form.projectTaskEndTimeField) {
          return this.$message.error(this.$t('common.projectManage.settingPassTimeTips'))
        }

        if (valid) {
          // 判断是否 有新建工单和编辑工单权限
          if (this.actionType === 'edit') {
            // 工单任务校验
            if(this.form.taskType === 'WORK_TASK') {
              if (!this.editAuth) return this.$message.error(this.$t('common.projectManage.taskEditAuth'))
              if (!this.allowEditTask) return this.$message.error(this.$t('common.projectManage.editTip1'))
            }

            if (!this.editPAASAuth && this.form.taskType === 'PAAS_TASK') return this.$message.error(this.$t('common.projectManage.paasEditAuth'))

            await this.saveTaskForm('taskExtend')
          } else if (this.actionType === 'draft') {
            //  如果是暂存状态 请求后端接口判断是否有编辑工单权限
            let params = {
              taskFormId: this.form.taskFormId,
              taskType: this.form.taskType,
            }

            let hasEditAuth = true
            if(this.form.taskType === 'WORK_TASK') {
              const { data } = await ProjectManage.isCanEditWorkOrder(params);
              hasEditAuth = data
            }
            if (!hasEditAuth) return this.$message.error(this.$t('common.projectManage.taskCreateAuth'))
            // 先保存工单类型的任务
            await this.saveTaskForm()
            this.goCreateTask()

          } else {
            // 新建任务 先判断任务名称是否重复
            await this.checkNameAndSize()
          }
        }
      })
    },


    async checkNameAndSize() {
      let params = {
        name: this.form.projectTaskName,
        projectId: this.projectId
      }
      await ProjectManage.checkNameAndSize(params).then((res) => {
        const { success, data, message } = res
        if (!success) return this.$message.error(message)

        if (data?.flag) {
          this.goCreateTask()
        } else {
          this.$message.error(data.msg)
        }
      })
    },

    // 跳转到新建工单or新建paas
    goCreateTask()  {
      this.isShow = false
      localStorage.setItem('projectTaskCreate', JSON.stringify(this.form))
      let fromId = window.frameElement.getAttribute('id');
      if(this.form.taskType === 'PAAS_TASK') {
        const paasList = this.typeOptions?.find(item => item. type === 'PAAS_TASK')?.formList ?? []
        const templateName = paasList?.find(item => item.id === this.form.taskFormId)?.name || ''
        getNodeInstanceRelation({formTemplateBizId: this.form.taskFormId }).then(res => {
          if(!res?.success) return this.$message.error(res?.message ?? '')

          // PAAS类型的任务，跳转到PAAS详情
          const { appId = ''} = res?.data ?? {}

          this.$platform.openTab({
            url: `/paas/#/template/edit?formId=${this.form.taskFormId}&appId=${appId}&from=project&projectId=${this.projectId}&additionalId=${this.form.additionalId || ''}&actionType=${this.actionType}`,
            title: this.$t('common.base.createModule', {data1: templateName}),
            id: `create_view_${this.form.taskFormId}_${this.form.additionalId}`,
            fromId,
            reload: true,
          });
        })
      }else {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageCreateTask,
          titleKey: '新建工单',
          params: `defaultTypeId=${this.form.taskFormId}&from=project&projectId=${this.projectId}&templateId=${this.templateId}&additionalId=${this.form.additionalId || ''}&actionType=${this.actionType}`,
          fromId
        })
      }
    },


    // 获取弹窗过滤的可用任务类型
    getTaskTypeData(actionType) {
      let params = {
        projectTypeId: this.templateId,
        queryTaskTypeScene: actionType === 'add'  ? 'CREATE'  : ''
      }

      if (actionType !== 'add') {
       delete params.queryTaskTypeScene
      }

      ProjectManage.queryTaskType(params).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        
        this.typeOptions = (res.data || []).map((item, index) => Object.freeze({
          id: index, // 解决默认选中所有的事件
          ...item
        }))
      })
    },

    // 设置表单字段规则配置 赋值表单
    projectToTaskForm() {
      let params = {
        fromBizId: this.projectId,
        additionalId: this.form.additionalId || '',
        // 以下字段后端要求固定写死
        useScene: 'PROJECT_TASK_RULE',
        toBizType: 'COMMON_TASK',
        fromBizType: 'PROJECT_MANAGER',
      }
      ProjectManage.insertSelectCallByAdditionalId(params).then(async (res) => {
        if (!res.success) return this.$message.error(res.message)

        let resultObj = await this.removeNullKey(res?.data || {})
        // 重新赋值
        this.taskformVal = resultObj
        // 初始化表单返回的人员数据 人员数据格式是数组
        if (this.taskformVal?.managerPerson) {
          this.taskformVal.managerPerson[0].userId = resultObj.managerPerson?.[0]?.id
          this.taskformVal.managerPerson[0].displayName = resultObj.managerPerson?.[0]?.name
          this.taskformVal.managerPerson[0].staffId = resultObj.managerPerson?.[0]?.staffId
        }
      })
    },

    // 过滤字段为空的
    removeNullKey(obj = {}){
      const result = {};
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          const element = obj[key];
          if (element !== null) {
            result[key] = element;
          }
        }
      }
      return result;
    },
    // updatePre(value) {
    //   this.form.preTaskId = (value || []).map((item) => item.id)
    // },
    async remoteMethodList(e){
      let params = {
        taskNameLike: e.keyword || '',
        projectId: this.projectId,
        id: this.form.id || '',
        pageNo: e.pageNum,
        pageSize: e.pageSize,
      }
      return ProjectManage.queryPreTaskListPro(params)
        .then(res => {
          if (!res || !res.data.list) return;
          res.data.list = res.data.list.map(item => Object.freeze({
            label: item.name,
            value: item.id,
            ...item
          }))
          return res.data;
        })
        .catch(err => console.info('searchInitiator function catch err', err))
    },

    // 获取前置任务
    getPreTaskOption() {
      let params = {
        projectId: this.projectId,
        id: this.form.id || '',
        pageNo: 1,
        pageSize: 500, // 后端要求固定
      }
      ProjectManage.queryPreTaskListPro(params).then((res) => {
        const { data, message, success } = res
        if (!success) return this.$message.error(message)
        this.preTaskOption = data?.list || []
      })
    },

    closeDialog() {
      this.isShow = false
    },

    // 改变任务类型
    handleSelectType() {
      this.fields = []
      let dataPath = this.$refs['cascaderType'].getCheckedNodes()?.[0]

      if (dataPath) {
        const { parent, data} = dataPath
        this.form.taskType = parent?.data?.type || '' // 任务类型
        this.form.taskFormName = data?.name || '' // 任务表单名称

        // 新建任务的时候，工单任务类型不展示保存按钮
        this.isShowNext = this.form.taskType !== 'COMMON_TASK'

        // 如果新建不是通用类型的，就不展示保存按钮
        this.isShowSaveBtn = !this.isShowNext

        if (this.form.taskType === 'COMMON_TASK') {
          // 通用任务直接当前弹窗渲染选中表单
          this.initFormList()
        }
        // 更换任务类型清空计划时间字段
        this.form.projectTaskStartTimeField = ''
        this.form.projectTaskEndTimeField = ''
        this.queryTimeFields();
      } 
    },

    initFormList() {
      if (this.form.taskFormId) {
       let params = {
          tableName: 'mission',
          templateId: this.form.taskFormId
        }
        ProjectManage.taskFieldList(params).then(async (res) => {
          const { data, message, success } = res
          if (!success) return this.$message.error(message)
          // 过滤掉 任务编号/任务名称/任务内容
          let filterType = ['missionNo', 'missionName', 'missionContent'];
          const copyFields = [];
          data.map((item) => {
            if (!filterType.includes(item.fieldName)) {
              copyFields.push(item)
            }
          })
          this.fields = copyFields

          // 计划开始时间和计划结束时间特殊处理，改为date日期格式
          this.fields = (this.fields || []).map((item) => {
            return {
              ...item,
              setting: item.fieldName === 'planStartTime' || item.fieldName === 'planEndTime' ? {dateType: 'date'} : item.setting
            }
          })

          // 过滤掉已经隐藏的
          this.fields = this.fields.filter((field) => !field.isHidden && (field.isVisible == undefined || field.isVisible))


          // 处理富文本
          if(this.form?.taskAttribute) {
            const formValue = {
              attribute: this.form.taskAttribute
            }
            const newValue = await FormUtil.initRichTextContent(this.fields, formValue);
            this.form.taskAttribute = newValue?.attribute || {};
          }

          if (this.form) {
            // 详情配置表单赋值 
            this.taskformVal = {
              planStartTime: this.form?.planStartTime || '',
              planEndTime: this.form?.planEndTime || '',
              expectTime: this.form.expectWorkTime || '',
              managerPerson: this.form.manager || [],
              ...this.form?.taskAttribute,
            }

            // 通用任务的id 字段唯一值校验
            this.taskformVal.id = this.form?.commonId || this.form?.taskBizId || ''
          }
        })
      }
    },  

    // 时间戳转为年月日
    fmt_datetime(val){
      if (!val) return ''
      return moment(val).format('YYYY-MM-DD')
    },

    updateForm({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      
      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }
      this.$set(this.taskformVal, fieldName, newValue);
    },


    paramsFun() {
      let filterForm =  _.cloneDeep(this.taskformVal)
      delete filterForm?.planEndTime
      delete filterForm?.planStartTime
      delete filterForm?.expectTime
      delete filterForm?.managerPerson

      let taskParams = {
        id: this.form.id || '',
        projectId: this.projectId, // 默认是1先设置
        ...this.form,
      }
      let manager_ = this.taskformVal?.managerPerson?.map(i=>{
        return {
          userId:i.id || i.userId,
          staffId:i.staffId,
          displayName: i.name || i.displayName
        }
      }) || []

      let commonTaskParams = {
        id: this.form.commonId || '',
        planEndTime: this.taskformVal?.planEndTime  || '',
        planStartTime: this.taskformVal?.planStartTime  || '',
        expectWorkTime: this.taskformVal?.expectTime || '',
        // 这里要做两层处理，一种是接口初始化返回的是数组格式，一种是用户自己下拉选择的数据格式是对象
        // manager: {
        //   userId: this.taskformVal?.managerPerson?.[0]?.id || this.taskformVal?.managerPerson?.userId || '',
        //   staffId: this.taskformVal?.managerPerson?.[0]?.staffId || this.taskformVal?.managerPerson?.staffId || '',
        //   displayName: this.taskformVal?.managerPerson?.[0]?.name || this.taskformVal?.managerPerson?.displayName || '',
        // },
        manager:manager_,
        taskAttribute: filterForm || {},
        deleteFiles: this.needServerDeleFiles
      }

      let detailParams = {}

      // 接口默认返回的计划时间删除
      delete taskParams?.planEndTime
      delete taskParams?.planStartTime

      if (this.actionType === 'draft') {
        detailParams = {
          updateTask: taskParams,
          addCommonTask: commonTaskParams,
        }
      } else {
        detailParams = {
          task: taskParams,
          commonTask: commonTaskParams,
        }
      }
      return detailParams
    },


     saveTaskForm(type) {
      // 工单任务
      this.pending = true
      ProjectManage.taskEditTask(this.form).then((res) => {
        this.pending = false
        if (!res.success) return this.$message.error(res.message)
        this.$message.success(this.$t('common.base.saveSuccess')) 
        // 保存成功，弹窗消失
        this.isShow = false
        this.$emit('updateList')
        if (type === 'taskExtend') {
          // 编辑工单跳转
          let fromId = window.frameElement.getAttribute('id');
          // 编辑paas跳转
          if(this.form.taskType === 'PAAS_TASK') {
            const { taskFormId = '', taskBizId = '', taskBizNumber = ''} = this.form
            getNodeInstanceRelation({formTemplateBizId: this.form.taskFormId, formContentId: taskBizId }).then(res => {
              if(!res?.success) return this.$message.error(res?.message ?? '')

              // PAAS类型的任务，跳转到PAAS详情
              const { appId = '', nodeInstanceId = ''} = res?.data ?? {}
              let url = `/paas/#/template/edit?formId=${taskFormId}&noHistory=1&formContentId=${taskBizId}&appId=${appId}&from=project&projectId=${this.projectId}&actionType=${this.actionType}&onlyEdit=true`
              if(nodeInstanceId) url=`${url}&nodeInstanceId=${nodeInstanceId}`

              this.$platform.openTab({
                url,
                title: `${this.$t('common.otherPageTitle.editForm')}${taskBizNumber}`,
                id: `edit_view_${taskBizNumber}`,
                fromId,
              });
            })
          }else {
            openAccurateTab({
              type: PageRoutesTypeEnum.PageEditTask,
              key: this.form.taskBizId,
              params: `from=project&projectId=${this.projectId}&templateId=${this.templateId}&actionType=${this.actionType}`,
              fromId
            })
          }
        }
      })
    },

    validPlanTime() {
      if(!this.openTime) return;

      // 项目的计划开始，完成时间
      const {proStart = '', proEnd = '',} = this.projectPlanTime
      // 任务的计划开始，完成时间
      const { planStartTime = '', planEndTime = ''} = this.taskformVal

      if(this.isTaskPlanStatTime) {
        if(proStart && planStartTime && proStart> planStartTime) return this.$t('common.validate.projectTaskPlanTime.v1');
        if(proEnd && planStartTime && proEnd < planStartTime) return this.$t('common.validate.projectTaskPlanTime.v2');
      }

      if(this.isTaskPlanEndTime) {
        if(proStart && planEndTime && proStart > planEndTime) return this.$t('common.validate.projectTaskPlanTime.v3')
        if(proEnd && planEndTime && proEnd < planEndTime)  return this.$t('common.validate.projectTaskPlanTime.v4')
      }

    },

    submitForm() {
      // 新建任务
      this.pending = true
      this.$refs['taskForm'].validate((valid, object) => {

        const msg = this.validPlanTime();
        if(msg) {
          this.pending = false
          return this.$message.error(msg)
        }

        if (valid) {
            // 校验paas任务的计划开始时间和计划完成时间字段是否一样
            if(this.form.taskType === 'PAAS_TASK'
                && this.form.projectTaskStartTimeField && this.form.projectTaskEndTimeField
                && this.form.projectTaskStartTimeField === this.form.projectTaskEndTimeField) {
              this.pending = false
              return this.$message.error(this.$t('common.projectManage.settingPassTimeTips'))
            }

            if (this.isCommonTask) {
              // 如果是项目详情跳转过来的保存任务
              this.$refs.taskFieldform.validate().then( async validated => {
                if (validated) { 
                  this.pending = false
                  let submitParams = await this.paramsFun()
                  this.$emit('submitTask', _.cloneDeep(submitParams), this.isFormEdit, this.actionType)
                } else {
                  this.pending = false
                  this.scrollError('err')
                  console.log('error submit!!');
                  return false;
                }
              })
            } else {
              this.saveTaskForm()
            }
        } else {
          this.pending = false
          this.scrollError('is-error')
          console.log('error submit!!');
          return false;
        }
      });

     
    },

    scrollError(ele) {
       // 处理两个表单字段过长，提交时无法在可视区域看到必填提示字段，采用滚动定位处理
       this.$nextTick(() => {
        let isError = document.getElementsByClassName(ele)
          isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth',
        })
      })
    },
    getDeleteFiles(files) {
      this.needServerDeleFiles = [...this.needServerDeleFiles, ...files]
    }
  }
}
</script>
<style lang="scss">
.create-project-task-dialog {
  .form-builder {
    width: 100% !important;
    padding: 0 !important;
  }
}
</style>
<style lang="scss" scoped>
.projectCustom {
  padding: 6px 12px 6px 20px;
  &-right {
    color: $color-primary-light-6;
    cursor: pointer;
    margin-left: 10px;
    &:hover {
      text-decoration: underline;
    }
  }
}

.task-form {
  max-height: 600px!important;
  ::v-deep .el-input__suffix {
    right: 1px;
  }
  .edit-task-form {
    width: 100%;
    padding: 0;
  }
  .w-100 {
    width: 100%;
  }
  .task-cascader {
    width: 100%;
  }
  .steps-wrap {
    margin-bottom: 20px;
  }
  .default-no {
    color: #8a8a8a;
    line-height: 32px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .task-num {
    color: $text-color-primary;
  }
  .task-rule-wrap {
    margin: 20px 0;
  }
}
</style>